<?php
namespace Admin\Controller;
use Think\Controller;
class BaseController extends Controller {
    private $model;
    private $tbl;
    private $perpage;
    public function _initialize(){
        $this->perpage=2;
       
        if(!session('?admin')){
        	$this->redirect('login/form');
        	exit;
        }
    }

    public function index($tbl,$morder='id desc'){
    	$this->model = D($tbl);
    	/*$data = $this->model->order($morder)->select();
        $this->assign('list',$data);*/
        $count      = $this->model->count();// 查询满足要求的总记录数
		$Page       = new \Think\Page($count,$this->perpage);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show       = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$list = $this->model->order($morder)->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('list',$list);// 赋值数据集
		$this->assign('page',$show);// 赋值分页输出

 		$this->display();
    }
    public function form($tbl){
    	$this->display();
    }
    public function add($tbl,$mfield = 'thumb'){
    	$this->model = D($tbl);
    	$data = I('post.');
        $data[$mfield]='';
        if(!empty($_FILES[$mfield]['name'])){
            $data[$mfield]=$this->uploadfile($mfield);
        }
               
    	if($this->model->create($data)){
    		$this->model->add();
    		$this->success('创建成功！',U('index'));
    	}
    	else{
    		$this->error($this->model->getError());
    	}
    }
    public function mod($tbl){
    	$this->model = D($tbl);
    	$id = I('get.id');
    	$one = $this->model->find($id);
    	//dump($one);exit;
    	$this->assign('one',$one);
    	$this->display();
    }

    protected function uploadfile($field,$tsize=150){
        $config = array(
            'maxSize'    =>    3145728,
            'rootPath'   =>    './Uploads/',
            'savePath'   =>    '',
            'saveName'   =>    array('uniqid',''),
            'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
            'autoSub'    =>    true,
            'subName'    =>    array('date','Ymd'),
        );

        $upload = new \Think\Upload($config);// 实例化上传类
        $upload->saveName = time().'_'.mt_rand();
        // 上传单个文件 
        $info   =   $upload->uploadOne($_FILES[$field]);
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功 获取上传文件信息
             $image = new \Think\Image();
             $image->open($config['rootPath'].$info['savepath'].$info['savename']);
             $image->thumb($tsize,$tsize,3)->save($config['rootPath'].$info['savepath'].'thumb_'.$info['savename']);
             return $info['savepath'].'thumb_'.$info['savename'];
        }
    }





}
?>